<?php

class CustomerController extends Controller
{
    public $_model;

    public function beforeAction($action)
    {
        $this->layout = Shop::module()->layout;
        return parent::beforeAction($action);
    }

    public function actionView()
    {
        $this->render('view', array(
            'model' => $this->loadModel(),
        ));
    }

    public function loadModel()
    {
        if ($this->_model === null) {
            if (isset($_GET['id']))
                $this->_model = Customer::model()->findbyPk($_GET['id']);
            if ($this->_model === null)
                throw new CHttpException(404, 'The requested page does not exist.');
        }
        return $this->_model;
    }

    public function actionAccount()
    {
        $model = Users::model()->findByPk(Yii::app()->user->id);
        $cart = Shop::getCartContent();
        $this->render('account', array(
            'model' => $model, 'cart' => $cart
        ));
    }

    public function actionCreate()
    {
        if ($model = Shop::getCustomer()) {
            $address = $model->address;
            $deliveryAddress = $model->deliveryAddress;
            $billingAddress = $model->billingAddress;
        } else {
            $model = new Customer;
        }

        if (isset($_POST['Customer'])) {
            $model->attributes = $_POST['Customer'];
            if (isset($_POST['Address'])) {
                $address = new Address;
                $address->attributes = $_POST['Address'];
                if ($address->save())
                    $model->address_id = $address->id;
            }

            if (isset($_POST['DeliveryAddress']) && !empty($_POST['is_delivery_same_address'])) {

                $deliveryAddress = new DeliveryAddress;
                $deliveryAddress->attributes = $_POST['DeliveryAddress'];
                if ($deliveryAddress->save()) {
                    $model->delivery_address_id = $deliveryAddress->id;
                }
            }

            if (isset($_POST['BillingAddress'])) {

                $billingAddress = new BillingAddress;
                $billingAddress->attributes = $_POST['BillingAddress'];
                if ($billingAddress->save()) {
                    $model->billing_address_id = $billingAddress->id;
                }
            }

            $address = new Address();
            $address->attributes = $_POST['BillingAddress'];
            $address->save();
            $model->address_id = $address->id;
            $model->email = $billingAddress->email;
            $model->save();

            if (!Yii::app()->user->isGuest)
                $model->user_id = Yii::app()->user->id;

            if ($model->save()) {
                if (!empty($_POST['is_create_account'])) {
                    // Create user
                    if (empty($model->user_id)) {
                        $user = new Users();
                        $user->attributes = $_POST['BillingAddress'];
                        $user->created_time = date('Y-m-d H:i:s');
                        $user->token = md5(uniqid(rand(), true));
                        $user->password = uniqid(rand(), true);
                        $user->status = 1;
                        $user->role = 0;
                        if ($user->save(false)) {
                            $model->user_id = $user->id;
                            $model->save(false);

                            // prepare mail content
                            $mailContent = $this->renderPartial('update_password', array('user' => $user), true);
                            $mailTitle = 'Please update password';
                            try {
                                if (!empty($toAddress)) {
                                    $mailer = Yii::app()->razMailer;
                                    $mailer->ClearAddresses();
                                    $mailer->sendEmail($user->email, $mailTitle, $mailContent);
                                }
                            } catch (Exception $e) {
                                Yii::log($e->getMessage(), 'error');
                            }

                        }
                    }
                }
                Yii::app()->user->setState('customer_id', $model->customer_id);
                $this->redirect(
                    array(
                        '/shop/order/confirm', 'customer' => $model->customer_id));
            }
        }
        
        $criteria = new CDbCriteria();
        $criteria->order = 'name asc';
        $countryList = Country::model()->findAll($criteria);
        
        $this->render('create', array(
            'customer' => $model,
            'billingAddress' => isset($billingAddress) ? $billingAddress : new BillingAddress(),
            'deliveryAddress' => isset($deliveryAddress) ? $deliveryAddress : new DeliveryAddress(),
            'countryList' => $countryList
        ));
    }
 
    public function actionEdit()
    {
        $model = Users::model()->findByPk(Yii::app()->user->id);
        
        if (isset($_POST['customer'])) 
        {
        	if($_POST['customer']['password'] == '') {
        		unset($_POST['customer']['password']);
        	} else {
        		$model->oldPassword = $model->password;
        	}
        	
        	$model->attributes = $_POST['customer'];
        	$model->country_id = $_POST['customer']['country_id'];
        	$model->updated_time = date('Y-m-d H:i:s');
        	
        	if($model->update()) {
        		
        		if (Yii::app()->user->isGuest) {
		            $id = Yii::app()->user->getState('customer_id');
		            $modelCustomer = Customer::model()->findByPk($id);
		        } else {
		            $modelCustomer = Customer::model()->find('user_id = :uid', array(
		                ':uid' => Yii::app()->user->id));
		        }
        
	            if (isset($_POST['customer'])) {
	            	if(!$modelCustomer) {
	            		$modelCustomer = new Customer;
	            		$modelCustomer->user_id = Yii::app()->user->id;
	            	}
	            	$modelCustomer->attributes = $_POST['customer'];
	            	
	            	//save address
	            	$_POST['customer']['country'] = ($_POST['customer']['country_id'])? $_POST['customer']['country_id'] :'';
	            	unset($_POST['customer']['country_id']);
	                $address = $modelCustomer->address;
	                if (!$address) $address = new Address;
	                $address->attributes = $_POST['customer'];
	                if ($address->save(false)) {
	                    $modelCustomer->address_id = $address->id;
	                }
	                
	                //save bill address
		            $billingAddress = $modelCustomer->billingAddress;
	                if (!$billingAddress) $billingAddress = new BillingAddress;
	
	                $billingAddress->attributes = $_POST['customer'];
	                if ($billingAddress->save(false)) {
	                    $modelCustomer->billing_address_id = $billingAddress->id;
	                    $modelCustomer->email = $billingAddress->email;
	                }
	                
	                //save customer
	                $modelCustomer->save();
	            }
         	}
        		
        	$this->redirect('/shop/customer/account');
        	
        }
        
        $criteria = new CDbCriteria();
        $criteria->order = 'name asc';
        $countryList = Country::model()->findAll($criteria);
        
        $this->render('edit', array(
            'model' => $model,
        	'countryList' => $countryList
        ));
    }

    public function actionUpdate($order = null)
    {
        if (Yii::app()->user->isGuest) {
            $id = Yii::app()->user->getState('customer_id');
            $model = Customer::model()->findByPk($id);
        } else
            $model = Customer::model()->find('user_id = :uid', array(
                ':uid' => Yii::app()->user->id));

        $error = 0;
        if (isset($_POST['Customer'])) {
            $model->attributes = $_POST['Customer'];
            if (isset($_POST['Address'])) {
                $address = $model->address;
                $address->attributes = $_POST['Address'];
                if ($address->save())
                    $model->address_id = $address->id;
            }
            
        	if (isset($_POST['BillingAddress'])) {
                $billingAddress = $model->billingAddress;
                if (!$billingAddress)
                    $billingAddress = new BillingAddress;

                $billingAddress->attributes = $_POST['BillingAddress'];
                if ($billingAddress->save()) {
                    $model->billing_address_id = $billingAddress->id;
                    $model->email = $billingAddress->email;
                } else {
                	$error = 1;
                }
            }
            
            if (isset($_POST['is_delivery_same_address'])) {
                $deliveryAddress = $model->deliveryAddress;
                if (!$deliveryAddress)
                    $deliveryAddress = new DeliveryAddress;

                $deliveryAddress->attributes = $_POST['DeliveryAddress'];
                if ($deliveryAddress->save()) {
                    $model->delivery_address_id = $deliveryAddress->id;
                } else {
                	$error = 1;
                }
            }

            $address = new Address();
            $address->attributes = $_POST['BillingAddress'];
            $address->save();
            $model->address_id = $address->id;

            if ($model->save(false)) {
                if (!empty($_POST['is_create_account'])) {
                    // Create user
                    if (empty($model->user_id)) {
                        $user = new Users();
                        $user->attributes = $_POST['BillingAddress'];
                        $user->created_time = date('Y-m-d H:i:s');
                        $user->token = md5(uniqid(rand(), true));
                        $user->password = uniqid(rand(), true);
                        $user->status = 1;
                        $user->role = 0;
                        if ($user->save(false)) {
                            $model->user_id = $user->id;
                            $model->save(false);

                            // prepare mail content
                            $mailContent = $this->renderPartial('update_password', array('user' => $user), true);
                            $mailTitle = 'Please update password';
                            try {
                                if (!empty($toAddress)) {
                                    $mailer = Yii::app()->razMailer;
                                    $mailer->ClearAddresses();
                                    $mailer->sendEmail($user->email, $mailTitle, $mailContent);
                                }
                            } catch (Exception $e) {
                                Yii::log($e->getMessage(), 'error');
                                $error = 1;
                            }
                        }
                    }
                }
                
                if(!$error) {
                	$this->redirect(
                    array(
                        '//shop/order/confirm', 'customer' => $model->customer_id));
                }
            }
        }

        $criteria = new CDbCriteria();
        $criteria->order = 'name asc';
        $countryList = Country::model()->findAll($criteria);

        $address = $model->address;
        $deliveryAddress = $model->deliveryAddress;
        $billingAddress = $model->billingAddress;

        $this->render('update', array(
            'customer' => $model,
            'address' => isset($address) ? $address : new Address,
            'deliveryAddress' => isset($deliveryAddress) ? $deliveryAddress : new DeliveryAddress,
            'billingAddress' => isset($billingAddress) ? $billingAddress : new BillingAddress,
            'countryList' => $countryList
        ));
    }

    public function actionDelete()
    {
        if (Yii::app()->request->isPostRequest) {
            $this->loadModel()->delete();

            if (!isset($_POST['ajax']))
                $this->redirect(array('index'));
        } else
            throw new CHttpException(400, 'Invalid request. Please do not repeat this request again.');
    }


    public function actionIndex()
    {
        $dataProvider = new CActiveDataProvider('Customer');
        $this->render('index', array(
            'dataProvider' => $dataProvider,
        ));
    }

    public function actionAdmin()
    {
        $model = new Customer('search');
        if (isset($_GET['Customer']))
            $model->attributes = $_GET['Customer'];

        $this->render('admin', array(
            'model' => $model,
        ));
    }

    /**
     * Performs the AJAX validation.
     * @param CModel the model to be validated
     */
    protected function performAjaxValidation($model)
    {
        if (isset($_POST['ajax']) && $_POST['ajax'] === 'customer-form') {
            echo CActiveForm::validate($model);
            Yii::app()->end();
        }
    }
}
